#_*_coding:utf-8_*_
import sys
import os
import time
import numpy as np
from skimage import io, feature
from skimage.color import rgb2gray
from PIL import ImageGrab

if __name__ == "__main__":
    screenshot = ImageGrab.grab()
    template_path = sys.argv[1]
    threshold = float(sys.argv[2])
                    
    # 读取图像并转换为灰度
    img_rgb = np.array(screenshot)
    debug_value = os.environ.get('DEBUG_LEVEL', '')
    if debug_value.isdigit():
        firename ='./autorecord/' + time.strftime("%H-%M-%S") + '.png'
        io.imsave(firename, img_rgb, check_contrast=False)
    img_gray = rgb2gray(img_rgb)
    template = io.imread(template_path, as_gray=True)

    template_h, template_w = template.shape[:2]

    # 使用skimage的match_template进行模板匹配
    result = feature.match_template(img_gray, template)

    # 找到匹配结果大于阈值的位置
    loc = np.where(result >= threshold)

    if len(loc[0]) < 1:
        print(0, 0)
    else:
        # 取第一个匹配位置
        y, x = loc[0][0], loc[1][0]
        # 计算中心点坐标
        center_x = x + template_w // 2
        center_y = y + template_h // 2
        print(center_x, center_y)

